package cn.ac.jaas.isc.vegetable.pbms.service.impl;

import cn.ac.jaas.isc.vegetable.common.core.util.R;
import cn.ac.jaas.isc.vegetable.common.security.service.VegetableUser;
import cn.ac.jaas.isc.vegetable.common.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ac.jaas.isc.vegetable.pbms.api.entity.ArcHouse;
import cn.ac.jaas.isc.vegetable.pbms.mapper.ArcHouseMapper;
import cn.ac.jaas.isc.vegetable.pbms.service.ArcHouseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 温室表
 *
 * @author 张高昌
 * @date 2022-05-02 09:38:48
 */
@Slf4j
@Service
@AllArgsConstructor
public class ArcHouseServiceImpl extends ServiceImpl<ArcHouseMapper, ArcHouse> implements ArcHouseService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveHouse(ArcHouse arcHouse) {
        List<ArcHouse> arcHouses = baseMapper.selectList(Wrappers.<ArcHouse>query().lambda().eq(ArcHouse::getHouseName, arcHouse.getHouseName()));
        if (arcHouses != null && arcHouses.size() > 0) {
            return R.failed("温室名称已存在");
        }
        VegetableUser user = SecurityUtils.getUser();
        arcHouse.setCreateTime(LocalDateTime.now());
        arcHouse.setCreateUser(user.getId());
        baseMapper.insert(arcHouse);
        log.info("添加温室成功");
        return R.ok(true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R updateHouseById(ArcHouse arcHouse) {
        LambdaQueryWrapper<ArcHouse> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ArcHouse::getHouseName, arcHouse.getHouseName())
                .ne(ArcHouse::getHouseId, arcHouse.getHouseId());
        List<ArcHouse> model = baseMapper.selectList(wrapper);
        if (model.size() > 0) {
            return R.failed("温室名称已存在");
        }

        VegetableUser user = SecurityUtils.getUser();
        arcHouse.setUpdateTime(LocalDateTime.now());
        arcHouse.setUpdateUser(user.getId());
        baseMapper.updateById(arcHouse);
        return R.ok(true);
    }

    @Override
    public R removeHouseById(Integer houseId) {
        ArcHouse arcHouse = baseMapper.selectById(houseId);
        if (arcHouse == null) {
            R.failed("温室不存在");
        }
        baseMapper.deleteById(houseId);
        return R.ok(true);
    }
}
